﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SimpleActor
{
    internal class FuncMessage<TServant, TResult> : MessageBase<TServant> where TServant : IActorServant
    {
        private readonly Func<TServant, Task<TResult>> func;
        private readonly TaskCompletionSource<TResult> source;

        public FuncMessage(string methodName, Func<TServant, Task<TResult>> func)
            : base(methodName)
        {
            this.func = func;
            this.source = new TaskCompletionSource<TResult>();
        }

        public Task<TResult> Task
        {
            get { return source.Task; }
        }

        public override void Invoke(TServant servant)
        {
            try
            {
                var t = func(servant);
                source.Connect(t);
            }
            catch (Exception ex)
            {
                source.TrySetException(ex);
                throw;
            }
        }

        public override void Abort(Func<Exception> newException)
        {
            var ex = newException();
            source.TrySetException(ex);
        }
    }
}
